package com.koron.order.linepatrol.uav.controller;

import cn.hutool.poi.excel.WorkbookUtil;
import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.EasyExcelUtils;
import com.koron.order.linepatrol.satellite.service.LinePatrolSatelliteService;
import com.koron.order.linepatrol.uav.bean.VO.LinePatrolUnv;
import com.koron.order.linepatrol.uav.bean.VO.TypeGroup;
import com.koron.order.linepatrol.uav.bean.dto.LinePatrolUnvDTO;
import com.koron.order.linepatrol.uav.bean.excel.LinePatrolExcel;
import com.koron.order.linepatrol.uav.bean.query.LinePatrolUnvQuery;
import com.koron.order.linepatrol.uav.converter.LinePatrolUnvConverter;
import com.koron.order.linepatrol.uav.excel.CustomStringStringConverter;
import com.koron.order.linepatrol.uav.excel.LinePatrolUnvExcelListener;
import com.koron.order.linepatrol.uav.service.LineUnvDefectPatrolDetailService;
import com.koron.order.overhaul.bean.dto.Equipment;
import com.koron.order.risk.base.excel.ErrorFillRowWriteHandler;
import com.koron.order.risk.feign.LineEquipmentFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @ClassName: LinePatrolUnvController
 * @Description:
 * @Date: 2023/2/9
 * @Author: 李一辰
 * @Version: 1.0
 **/
@Slf4j
@RestController
@RequestMapping("/linePatrolUnvController")
@Api(tags = "无人机缺陷列表页面")
public class LineUnvDefectPatrolDetailController {



    @Autowired
    private LineUnvDefectPatrolDetailService lineUnvDefectPatrolDetailService;
    @Autowired
    private LinePatrolSatelliteService linePatrolSatelliteService;
    @Autowired
    private LineEquipmentFeign equipmentFeign;

    @Autowired
    private LinePatrolUnvConverter linePatrolUnvConverter;
    private String getCurrDs() {
        return ThreadLocalContext.get().getCurrDs();
    }

    @GetMapping("/getById")
    @ApiOperation("根据id查询缺陷详情页面")
    public Response<LinePatrolUnv> getById(String id){
        LinePatrolUnv linePatrolUnv = ADOConnection.runTask(getCurrDs(), lineUnvDefectPatrolDetailService, "getById", LinePatrolUnv.class, id);
        return Response.ok(linePatrolUnv);
    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "根据id查询(详细记录)")
    @GetMapping("selectDetailById")
    public Response<LinePatrolUnvDTO> selectDetailById(String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), lineUnvDefectPatrolDetailService, "selectDetailById", LinePatrolUnvDTO.class, id));
    }

    @GetMapping("/list")
    @ApiOperation("查询缺陷列表")
    public Response<PageInfo<LinePatrolUnv>> list(LinePatrolUnvQuery linePatrolUnvQuery, PageQuery pageQuery){
        PageInfo<LinePatrolUnv> linePatrolUnv = ADOConnection.runTask(getCurrDs(), lineUnvDefectPatrolDetailService, "list", PageInfo.class, linePatrolUnvQuery,pageQuery);
        return Response.ok(linePatrolUnv);
    }

    @PostMapping("/Insert")
    @ApiOperation("新建")
    public Response<LinePatrolUnvQuery> Insert( LinePatrolUnvQuery linePatrolUnvQuery){
        Boolean linePatrolUnv = ADOConnection.runTask(getCurrDs(), lineUnvDefectPatrolDetailService, "Insert", Boolean.class, linePatrolUnvQuery);
        return Response.ok(linePatrolUnvQuery);
    }
    @PutMapping("/update")
    @ApiOperation("更新")
    public Response<LinePatrolUnv> update( @RequestBody  LinePatrolUnv linePatrolUnv){
        Boolean lineDefectPatrolUnv = ADOConnection.runTask(getCurrDs(), lineUnvDefectPatrolDetailService, "update", Boolean.class, linePatrolUnv);
        return Response.ok(linePatrolUnv);
    }






    @SneakyThrows
    @ApiOperation(value = "下载无人机巡视模板")
    @GetMapping("/template")
    public void template1(HttpServletResponse response) {
        String path = "excel/patrol_unv_defect.xlsx";
        ClassPathResource classPathResource = new ClassPathResource(path);
        Workbook book = WorkbookUtil.createBook(classPathResource.getInputStream());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("无人机巡视缺陷报告导入单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        book.write(response.getOutputStream());
    }



    @SneakyThrows
    @ApiOperation(value = "导入")
    @PostMapping("/import")
    public Response importFile(@RequestParam("file") MultipartFile file, @RequestParam(required = true) String defectId){
        CustomStringStringConverter customStringStringConverter = new CustomStringStringConverter();
        LinePatrolUnvExcelListener linePatrolUnvExcelListener = new LinePatrolUnvExcelListener(lineUnvDefectPatrolDetailService,linePatrolUnvConverter,equipmentFeign,defectId);
        EasyExcel.read(file.getInputStream(), LinePatrolExcel.class, linePatrolUnvExcelListener)
                .registerConverter(customStringStringConverter)
                .headRowNumber(1)
                .sheet(0)
                .doRead();
        if (linePatrolUnvExcelListener.getExcelErrors().size() != 0) {
            String path = "excel/patrol_unv_defect_error.xlsx";
            ClassPathResource classPathResource = new ClassPathResource(path);
            // 输出错误文件
            String filename = CodeTools.getCodeNo("LinePatrolUnv", 3);
            String tempPath = EasyExcelUtils.createTempFile(filename, "xlsx");
            log.warn("导入失败，错误文件在：{}", tempPath);
            EasyExcel.write(tempPath)
                    .withTemplate(classPathResource.getInputStream())
                    .head(LinePatrolExcel.class)
                    .needHead(false)
                    .registerConverter(customStringStringConverter)
                    .registerWriteHandler(new ErrorFillRowWriteHandler(linePatrolUnvExcelListener.getExcelErrors()))
                    .sheet(0)
                    .doWrite(linePatrolUnvExcelListener.getErrorRisk());
            return Response.ok("temp/" + filename + ".xlsx");
        }
        return Response.ok("导入成功", null);
    }


    // 所有的线路设备数据
    @ApiOperation(value = "所有的线路,杆塔设备数据")
    @GetMapping("/allEquipment")
    public List<Equipment> allLineEquipment() {
        return ADOConnection.runTask(getCurrDs(), linePatrolSatelliteService, "allEquipments", List.class);
    }


// 所有的线路部件
    @ApiOperation(value = "所有的线路部件")
    @GetMapping("/allLineUnit")
    public List<TypeGroup> allLineUnit(){
        return ADOConnection.runTask(getCurrDs(), lineUnvDefectPatrolDetailService, "getTypeGroup", List.class);
    }

}
